<template>
  <view class="list-page">
    <!-- 搜索栏 -->
    <view class="list-search-bar">
      <view class="list-search-input">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input v-model="queryParams.deptName" class="list-input" placeholder="搜索部门名称" @input="handleSearchInput"
               @confirm="handleSearch"/>
        <uni-icons v-if="queryParams.deptName" type="clear" size="16" color="#999" @click="handleClear"></uni-icons>
      </view>
      <view class="list-filter-btn" @click="toggleFilter">
        <uni-icons type="filter" size="14" color="#666"></uni-icons>
        <text>筛选</text>
      </view>
    </view>

    <!-- 筛选抽屉 -->
    <uni-popup ref="filterPopup" type="right" :mask-click="false">
      <view class="list-filter-drawer">
        <view class="list-filter-header">
          <text class="list-filter-title">高级筛选</text>
          <uni-icons type="close" size="20" @click="closeFilter"></uni-icons>
        </view>
        <view class="list-filter-content">
          <view class="list-filter-item">
            <text class="list-filter-label">状态</text>
            <BottomSelect v-model="queryParams.status" :options="statusOptions" value-field="value" label-field="text"
                          placeholder="请选择状态" title="选择状态"/>
          </view>
        </view>
        <view class="list-filter-footer">
          <view class="btn btn-reset" @click="handleFilterReset">重置</view>
          <view class="btn btn-confirm" @click="handleFilterConfirm">确定</view>
        </view>
      </view>
    </uni-popup>

    <!-- 操作按钮栏 -->
    <view class="list-action-bar">
      <view class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['system:dept:add'])">
        <uni-icons type="plus" size="14" color="#007aff"/>
        <text>新增</text>
      </view>
      <view class="btn btn-default" @click="toggleExpandAll">
        <uni-icons :type="isExpandAll ? 'minus' : 'plus'" size="14" color="#666"/>
        <text>{{ isExpandAll ? '折叠' : '展开' }}</text>
      </view>
      <view class="btn btn-default" @click="handleRefresh">
        <uni-icons type="reload" size="14" color="#666"/>
        <text>刷新</text>
      </view>
    </view>

    <!-- 部门树形列表 -->
    <view class="list-content">
      <view v-for="dept in flatDeptList" :key="dept.deptId" class="list-item" :class="`level-${dept.level}`"
            :style="{ paddingLeft: (dept.level * 20) + 'px' }" @click="handleUpdate(dept)">
        <view class="list-avatar">
          <uni-icons :type="getDeptIcon(dept)" size="24" :color="getDeptIconColor(dept)"></uni-icons>
        </view>
        <view class="list-info">
          <view class="list-header">
            <view class="title-with-expand">
              <view class="expand-icon" v-if="dept.children && dept.children.length > 0"
                    @click.stop="toggleDeptExpand(dept)">
                <uni-icons :type="dept.expanded ? 'minus' : 'plus'" size="18" color="#666"></uni-icons>
              </view>
              <text class="list-title">{{ dept.deptName }}</text>
            </view>
            <view class="status-badge" :class="dept.status === '0' ? 'status-normal' : 'status-disabled'">
              {{ dept.status === '0' ? '正常' : '停用' }}
            </view>
          </view>
          <view class="list-details">
            <view class="detail-item">
              <uni-icons type="list" size="14" color="#999"/>
              <text class="detail-text">ID：{{ dept.deptId }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="list" size="14" color="#999"/>
              <text class="detail-text">负责人：{{ dept.leader }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="up-down" size="14" color="#999"/>
              <text class="detail-text">排序：{{ dept.orderNum }}</text>
            </view>
            <view class="detail-item" v-if="dept.phone">
              <uni-icons type="phone" size="14" color="#999"/>
              <text class="detail-text">{{ dept.phone }}</text>
            </view>
            <view class="detail-item" v-if="dept.email">
              <uni-icons type="email" size="14" color="#999"/>
              <text class="detail-text">{{ dept.email }}</text>
            </view>
          </view>
        </view>
        <view class="list-actions">
          <view class="action-btn action-primary" @click.stop="handleUpdate(dept)"
                v-if="checkPermission(['system:dept:edit'])">
            <uni-icons type="compose" size="14" color="#007aff"/>
            <text class="action-text">编辑</text>
          </view>
          <view class="action-btn action-success" @click.stop="handleAddChild(dept)"
                v-if="checkPermission(['system:dept:add'])">
            <uni-icons type="plus" size="14" color="#34c759"/>
            <text class="action-text">新增</text>
          </view>
          <view class="action-btn" :class="dept.status === '0' ? 'action-warning' : 'action-success'"
                @click.stop="handleStatusChange(dept)" v-if="checkPermission(['system:dept:edit'])">
            <uni-icons :type="dept.status === '0' ? 'close' : 'checkmarkempty'" size="14"
                       :color="dept.status === '0' ? '#ff9500' : '#34c759'"/>
            <text class="action-text">{{ dept.status === '0' ? '停用' : '启用' }}</text>
          </view>
          <view class="action-btn action-danger" @click.stop="handleDelete(dept)"
                v-if="checkPermission(['system:dept:remove'])">
            <uni-icons type="trash" size="14" color="#ff3b30"/>
            <text class="action-text">删除</text>
          </view>
        </view>
      </view>
    </view>

    <view v-if="!loading && deptList.length === 0" class="list-empty">
      <uni-icons type="home" size="48" color="#ddd"/>
      <text class="list-empty-text">暂无部门数据</text>
      <button class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['system:dept:add'])">添加部门</button>
    </view>
  </view>
</template>

<script setup>
import {computed, getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {delDept, listDept, updateDept} from '@/api/system/dept'
import {handleTree} from '@/utils/ruoyi'

import {usePermission} from '@/utils/permission'
import {BottomSelect} from '@/components/select'

const {proxy} = getCurrentInstance()


const checkPermission = usePermission()

// 数据定义
const deptList = ref([])
const total = ref(0)
const loading = ref(false)
const isExpandAll = ref(false)
const filterPopup = ref(null)
const expandTrigger = ref(0) // 用于触发展开状态变化
let searchTimer = null

// 计算属性 - 扁平化的部门列表用于渲染
const flatDeptList = computed(() => {
  // 依赖 expandTrigger 来触发重新计算
  expandTrigger.value
  return flattenDeptTree(deptList.value)
})

// 查询参数
const queryParams = reactive({
  deptName: '',
  status: ''
})

// 状态选项
const statusOptions = [
  {value: '', text: '全部状态'},
  {value: '0', text: '正常'},
  {value: '1', text: '停用'}
]

// 页面加载
onMounted(() => {
  getList()
})

// 获取部门列表
async function getList() {
  loading.value = true

  try {
    const response = await listDept(queryParams)
    if (response.code === 200) {
      const data = response.data || []
      const treeData = handleTree(data, 'deptId', 'parentId', 'children')
      // 初始化展开状态
      deptList.value = initExpandState(treeData)
      total.value = data.length
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    proxy.$modal.showToast('获取部门列表失败')
  } finally {
    loading.value = false
  }
}

// 筛选相关函数
function toggleFilter() {
  filterPopup.value.open()
}

function closeFilter() {
  filterPopup.value.close()
}

function handleFilterConfirm() {
  closeFilter();
  handleQuery()
}

function handleFilterReset() {
  Object.assign(queryParams, {deptName: '', status: ''})
}

function handleSearchInput() {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    handleQuery()
  }, 300)
}

function handleSearch() {
  handleQuery()
}

function handleClear() {
  queryParams.deptName = '';
  handleQuery()
}

// 查询
function handleQuery() {
  getList()
}

// 业务操作方法
function handleAdd() {
  uni.navigateTo({
    url: './edit?mode=add'
  })
}

function handleAddChild(dept) {
  uni.navigateTo({
    url: `./edit?mode=add&parentId=${dept.deptId}`
  })
}

function handleUpdate(dept) {
  uni.navigateTo({
    url: `./edit?mode=edit&deptId=${dept.deptId}`
  })
}

async function handleDelete(dept) {
  try {
    await proxy.$modal.confirm(`确认要删除部门"${dept.deptName}"吗？`)

    const response = await delDept(dept.deptId)
    if (response.code === 200) {
      proxy.$modal.showToast('删除成功')
      getList()
    }
  } catch (error) {
    console.error('删除部门失败:', error)
  }
}

async function handleStatusChange(dept) {
  try {
    const newStatus = dept.status === '0' ? '1' : '0'
    const statusText = newStatus === '0' ? '启用' : '停用'

    await proxy.$modal.confirm(`确认要${statusText}部门"${dept.deptName}"吗？`)

    const updateData = {
      deptId: dept.deptId,
      status: newStatus
    }

    const response = await updateDept(updateData)
    if (response.code === 200) {
      dept.status = newStatus
      proxy.$modal.showToast(`${statusText}成功`)
    }
  } catch (error) {
    console.error('修改状态失败:', error)
  }
}

function toggleExpandAll() {
  isExpandAll.value = !isExpandAll.value
  // 更新所有部门的展开状态
  updateAllExpandState(deptList.value, isExpandAll.value)
  // 触发重新计算
  expandTrigger.value++
}

function handleRefresh() {
  getList()
}

// 初始化展开状态
function initExpandState(deptList, level = 0) {
  return deptList.map(dept => {
    dept.expanded = isExpandAll.value
    dept.level = level
    if (dept.children && dept.children.length > 0) {
      dept.children = initExpandState(dept.children, level + 1)
    }
    return dept
  })
}

// 更新所有展开状态
function updateAllExpandState(deptList, expanded) {
  deptList.forEach(dept => {
    dept.expanded = expanded
    if (dept.children && dept.children.length > 0) {
      updateAllExpandState(dept.children, expanded)
    }
  })
}

// 切换单个部门展开状态
function toggleDeptExpand(dept) {
  dept.expanded = !dept.expanded
  // 触发重新计算
  expandTrigger.value++
}

// 扁平化部门树
function flattenDeptTree(deptList, level = 0) {
  const result = []

  deptList.forEach(dept => {
    dept.level = level
    result.push(dept)

    // 修复展开逻辑：当全局展开或者单个部门展开时才显示子部门
    if (dept.children && dept.children.length > 0) {
      const shouldExpand = isExpandAll.value || dept.expanded
      if (shouldExpand) {
        result.push(...flattenDeptTree(dept.children, level + 1))
      }
    }
  })

  return result
}

// 获取部门图标
function getDeptIcon(dept) {
  // 根据部门层级使用不同图标
  if (dept.parentId === 0 || !dept.parentId) {
    return 'building' // 顶级部门使用建筑图标
  } else if (dept.children && dept.children.length > 0) {
    return 'folder' // 有子部门的部门使用文件夹图标
  } else {
    return 'home' // 叶子部门使用房屋图标
  }
}

// 获取部门图标颜色
function getDeptIconColor(dept) {
  // 根据部门层级使用不同颜色
  if (dept.parentId === 0 || !dept.parentId) {
    return '#1890ff' // 顶级部门：蓝色
  } else if (dept.children && dept.children.length > 0) {
    return '#52c41a' // 有子部门的部门：绿色
  } else {
    return '#faad14' // 叶子部门：橙色
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/tree-page.scss';
</style>